<template>
  <div class="login-container">
    <div class="form-container">
      <!-- 登录表单 -->
      <div class="login-form">
        <h2>登录</h2>
        <form @submit.prevent="handleLogin">
          <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" v-model="username" required placeholder="请输入用户名" />
          </div>
          <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" v-model="password" required placeholder="请输入密码" />
          </div>
          <button type="submit" class="login-button">登录</button>
        </form>
      </div>

      <!-- 注册引导 -->
      <div class="register-button">
        <h2>没有账号？</h2>
        <p>点击下方按钮注册新账号</p>
        <button @click="goToRegister">注册</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/authStore'
import { useMenuStore } from '@/stores/menuStore'
import { loginApi } from '@/api/auth'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()
const menuStore = useMenuStore()

const username = ref('')
const password = ref('')

// 获取指定账号的锁定时间
function getLockUntil(username) {
  return Number(localStorage.getItem(`loginLockUntil_${username}`) || 0)
}

// 设置指定账号的锁定时间
function setLockUntil(username, time) {
  localStorage.setItem(`loginLockUntil_${username}`, time)
}

// 获取指定账号的错误次数
function getErrorCount(username) {
  return Number(localStorage.getItem(`loginErrorCount_${username}`) || 0)
}

// 设置指定账号的错误次数
function setErrorCount(username, count) {
  localStorage.setItem(`loginErrorCount_${username}`, count)
}

// 清除指定账号的锁定和错误次数
function clearLockInfo(username) {
  localStorage.removeItem(`loginLockUntil_${username}`)
  localStorage.removeItem(`loginErrorCount_${username}`)
}

// 倒计时弹窗
function showLockCountdown(lockUntil) {
  let timer = null
  let left = Math.ceil((lockUntil - Date.now()) / 1000)
  ElMessageBox.alert(
    `账户已锁定，请${Math.floor(left / 60)}分${left % 60}秒后再试`,
    '登录已锁定',
    {
      type: 'error',
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      callback: () => {
        if (timer) clearInterval(timer)
      }
    }
  )
  timer = setInterval(() => {
    left = Math.ceil((lockUntil - Date.now()) / 1000)
    if (left <= 0) {
      ElMessageBox.close()
      clearInterval(timer)
    } else {
      document.querySelector('.el-message-box__message').innerHTML =
        `账户已锁定，请${Math.floor(left / 60)}分${left % 60}秒后再试`
    }
  }, 1000)
}

const handleLogin = async () => {
  // 检查当前账号是否被锁定
  const lockUntil = getLockUntil(username.value)
  if (lockUntil && Date.now() < lockUntil) {
    showLockCountdown(lockUntil)
    return
  }

  try {
    const res = await loginApi(username.value, password.value)
    // console.log('[Login] 登录响应:', res) // 添加调试信息

    if (res.code === 200 || res.code === 0) {
      // 登录成功
      clearLockInfo(username.value)
      ElMessageBox.alert('密码正确，登录成功', '登录成功', {
        type: 'success'
      })

      // 修复：正确解构后端返回的数据
      const { userInfo, token, refreshToken, expiresIn } = res.data
      // console.log('[Login] 解构后的数据:', { userInfo, token, refreshToken, expiresIn })

      // 保存认证数据
      authStore.setAuthData({
        token,
        refreshToken,
        user: userInfo
      })

      // 获取用户菜单
      try {
        await menuStore.fetchUserMenuTree()
        // console.log('[Login] 用户菜单获取成功')
      } catch (error) {
        console.error('[Login] 获取用户菜单失败:', error)
      }

      setTimeout(() => {
        router.push({ name: 'DashboardView' })
      }, 1000)
    } else {
      // 密码错误处理
      let count = getErrorCount(username.value) + 1
      if (count >= 5) {
        // 锁定半小时
        const lockTime = Date.now() + 30 * 60 * 1000
        setLockUntil(username.value, lockTime)
        setErrorCount(username.value, 0)
        showLockCountdown(lockTime)
      } else {
        setErrorCount(username.value, count)
        ElMessage.error(
          (res.message ? res.message : `密码错误，还可尝试${5 - count}次`) +
          (5 - count === 0 ? '，已锁定半小时' : '')
        )
      }
    }
  } catch (error) {
    console.error('[Login] 登录错误:', error)
    ElMessage.error('登录失败，请检查网络连接')
  }
}

const goToRegister = () => {
  router.push({ name: 'RegisterPage' })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('../../img/登录注册背景图.png');
  /* 替换为你的背景图路径 */
  background-size: cover;
  background-position: center;
}

.form-container {
  display: flex;
  width: 650px;
  height: 350px;
  background-color: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(4px);
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.login-form {
  flex: 1;
  padding: 30px;
  background-color: white;
}

.register-button {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border-left: 1px solid #e0e0e0;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.login-button,
.register-button button {
  width: 100%;
  padding: 10px;
  background-color: #71a4b9;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-button:hover,
.register-button button:hover {
  background-color: #2093a2;
}

.register-button button {
  width: 150px;
  margin-top: 15px;
}
</style>